
require 'appwiki/base/base_controller.rb'
require 'appwiki/group/group.rb'
require 'appwiki/user/user.rb'

class GroupController < BaseController

    def whereami() [__FILE__] end

    #
    # should be the leaf
    # 
    def preload
      @group = nil
      @group = Group.find_by_uid(@workingpath.last) if @workingpath.length
      @user = nil
      @user = User.find_by_id( session[:userid] ) if session[:userid]
      @visitingself = false
      @visitingself = true if @user && @group && @session[:username] == @group[:title]
      puts "GroupController: person is #{@user} group is #{@group}" if @@debug
    end

    def join
      # valid user?
      if !@user
        flash[:notice => "You must be logged in to join a group" ]
        render :action => "error"
        return
      end
      if !@group
        flash[:notice] = "No group by that name"
        render :action => "error"
        return
      end
      # already a member?
      if @group.is_a_member?(@user)
        flash[:notice] = "You are already a member of this group"
        render :action => "error"
        return
      end
      # join
      @group.join @user
      render :action => "join"
    end

    def evict
      if !@group
        render :action => "error"
        return
      end
      if !@user
        render :action => "error"
        return
      end
      if @user.id != @group.sponsor
        render :action => "error"
        return
      end
      @evict = User.find_named(params[:user])
      if !@evict
        render :action => "error"
        return
      end
      @group.leave @evict
    end

    def invite
      if !@group
        render :action => "error"
        return
      end
      if !@user
        render :action => "error"
        return
      end
      if @user.id != @group.sponsor
        render :action => "error"
        return
      end
      @invite = User.find_named(params[:user])
      if !@invite
        render :action => "error"
        return
      end
      @group.join @invite
    end

    def leave
      # valid user?
      if !@user
        flash[:notice] = "You must be logged in to leave a group"      
        render :action => "error"
        return
      end
      if !@group
        flash[:notice] = "No group by that name"
        render :action => "error"
        return
      end
      # not already a member?
      if !@group.is_a_member?(@user)
        flash[:notice] = "You are not even a member"
        render :action => "error"
        return
      end
      # leave
      @group.leave @user
      render :action => "leave"
    end

    def all
      # show all groups
      @results = Group.find(:all, :order => "created_at DESC", :offset => 0, :limit => 100)
      render :action => "all"
    end

    def groupsof
      # show groups a named user is in
      @user = User.find_named(params[:user])
      if !@user
        flash[:notice] = "No user by that name"
        render :action => "error"
        return
      end
      @results = Group.get_memberships(@user);
    end

    def membersof
      # show members of a named group
      if !@group
        flash[:notice] = "No group by that name"
        render :action => "error"
        return
      end
      @groupname = @group.uid
      @users = @group.get_members()
      render :action => "membersof"
    end

    def index
      membersof
    end

    #
    # find sponsor of this group if any
    #
    def sponsored
      @user = User.find_named(params[:user])
      if @user
        @results = Group.find(:all, :conditions => ["sponsor = ?", @user.id], :order => "created_at DESC", :offset => 0, :limit => 10)
      else
        @results = []  #Group.find(:all, :order => "created_at DESC", :offset => 0, :limit => 10)
      end
      render :action => "all"
    end

    #
    # create a group
    #
    def edit

      # must be logged in
      if !@user
        flash[:notice] = "You must be logged in to edit a group"      
        render :action => "error"
        return
      end

      # editing existing group?
      if !@group && @params[:id] && @params[:id].length > 0
        @group = Group.find(:first, :conditions => ["id = ?",params[:id] ] )
      end
      
      # try this
      if !@group && @params[:uid]
        @group = Group.find(:first, :conditions => ["uid = ?",params[:uid] ] )
      end

      # must be owner
      if @group && @user && @user.id != @group.sponsor
        flash[:notice] = "Only sponsor can modify a group"      
        render :action => "error"
        return
      end

      # create if new
      @params[:sponsor] = @user.id if @user
      @group = Group.new if !@group
      @group.set(@params)

      # submit?
      if params[:submit]

        # save the group
        if @group.save

          # join
          @group.join @user

          # save depiction if any
          if @params['depiction']
            depiction,err = BaseUtils.save_file({
                    :site=>@domainreversed,
                    :blob=>@params['depiction'],
                    :name=>@group.uid,
                    :thumb=>true
                    })
            @group.depiction = depiction
            @group.update
            if !@group.depiction
              puts "group_controller::profile() failed depiction save" if @@debug
              flash[:warning] = "Sorry, failed to save your depiction! #{err}"
              render :action => "edit"
              return
            end
          end

          if @user
            redirect_to :url => "/#{@group.uid}"
          else
            redirect_to :url => "/#{@group.uid}/sponsor"
          end

        end
      end

      @group.errors.each { |x,y| puts "group::setxxx error #{x} #{y}" } if @@debug

      # just show edit form with errors possibly
      render :action => "edit"
    end

    def xml

      # show members of a named group
      if !@group
        flash[:notice] = "No group by that name"
        render :action => "error"
        return
      end

      @groupname = @group.uid
      @users = @group.get_members()
      @users.each do |user|
        # do something
      end

      writeline '<?xml version="1.0" encoding="UTF-8"?>'
      writeline '<RelationViewerData>'
      writeline ''
      writeline '<Settings appTitle="' + @group.title + '" WWWLinkTargetFrame="_self" startID="DanSiegel" defaultRadius="170" maxRadius="240" contextRadius="230">'
      writeline ''
      writeline ''
      writeline '<RelationTypes>'
      writeline '<DirectedRelation color="0x85CDE4" lineSize="3" labelText="parent-child" letterSymbol="P" />'
      writeline '<UndirectedRelation color="0xDD7711" lineSize="4" labelText="association" letterSymbol="B"/>'
      writeline '</RelationTypes>'
      writeline '<NodeTypes>'
      writeline '<Person />'
      writeline '</NodeTypes>'
      writeline '</Settings>'
      writeline ''
      writeline '<Nodes>'
      writeline '<Person id="DanSiegel" name="Dan Siegel" hops="3" imageURL="/files/.DanSiegel.jpg"  linkURL="/DanSiegel"/>'
      writeline '<Person id="JennyYancey" name="Jenny Yancey" hops="" imageURL="/files/.JennyYancey.jpg"  linkURL="/JennyYancey"/>'
      writeline '<Person id="weezie" name="WeezieYancey" hops="" imageURL="/files/.weezie.jpg"  linkURL="/weezie"/>'
      writeline '<Person id="Satchel" name="Satchel Yancey" hops="" imageURL="/files/.Satchel.jpg"  linkURL="/Satchel"/>'
      writeline ''
      writeline '<Person id="GrammaYancey" name="Gramma Yancey" hops="" imageURL="/files/.GrammaYancey.jpg"  linkURL="/GrammaYancey"/>'
      writeline ''
      writeline '<Person id="GrandmaSiegel" name="Grandma Siegel" hops="" imageURL="/files/.GrandmaSiegel.jpg"  linkURL="/GrandmaSiegel"/>'
      writeline '</Nodes>'
      writeline ''
      writeline '<Relations>'
      writeline ''
      writeline ''
      writeline '<DirectedRelation  fromID="GrandmaSiegel" quality="50" toID="DanSiegel"/>'
      writeline '<DirectedRelation  fromID="GrammaYancey" quality="50" toID="JennyYancey"/>'
      writeline '<DirectedRelation  fromID="GrandmaSiegel" quality="50" toID="JennyYancey"/>'
      writeline '<DirectedRelation  fromID="GrammaYancey" quality="50" toID="DanSiegel"/>'
      writeline '<DirectedRelation  fromID="DanSiegel" quality="50" toID="weezie"/>'
      writeline '<DirectedRelation  fromID="DanSiegel" quality="50" toID="Satchel"/>'
      writeline '<DirectedRelation  fromID="JennyYancey" quality="50" toID="weezie"/>'
      writeline '<DirectedRelation  fromID="JennyYancey" quality="50" toID="Satchel"/>'
      writeline '<UndirectedRelation  fromID="JennyYancey" quality="50" toID="DanSiegel"/>'
      writeline '<UndirectedRelation  fromID="weezie"  toID="Satchel"/>'
      writeline '<UndirectedRelation  fromID="GrammaYancey"  toID="GrandmaSiegel"/>'
      writeline '</Relations>'
      writeline '</RelationViewerData>'
      render :layout => "", :nothing => true, :content_type => 'text/xml'
    end

end
